﻿namespace TuanHA_Combat_Routine
{
    using Styx.TreeSharp;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.CompilerServices;
    using System.Threading;

    public class ThrottlePasses : Decorator
    {
        private int _count;
        private DateTime _end;
        private RunStatus _limitStatus;

        public ThrottlePasses(int timeSeconds, Composite child) : this(1, TimeSpan.FromSeconds((double) timeSeconds), RunStatus.Failure, child)
        {
        }

        public ThrottlePasses(TimeSpan timeFrame, Composite child) : this(1, timeFrame, RunStatus.Failure, child)
        {
        }

        public ThrottlePasses(int Limit, int timeSeconds, Composite child) : this(Limit, TimeSpan.FromSeconds((double) timeSeconds), RunStatus.Failure, child)
        {
        }

        public ThrottlePasses(int Limit, TimeSpan ts, Composite child) : this(Limit, ts, RunStatus.Failure, child)
        {
        }

        public ThrottlePasses(int limit, TimeSpan timeFrame, RunStatus limitStatus, Composite child) : base(child)
        {
            this.TimeFrame = timeFrame;
            this.Limit = limit;
            this._end = DateTime.MinValue;
            this._count = 0;
            this._limitStatus = limitStatus;
        }

        protected override IEnumerable<RunStatus> Execute(object context)
        {
            if ((DateTime.Now >= this._end) || (this._count < this.Limit))
            {
                this.DecoratedChild.Start(context);
                while (this.DecoratedChild.Tick(context) == RunStatus.Running)
                {
                    yield return RunStatus.Running;
                }
                this.DecoratedChild.Stop(context);
                if (DateTime.Now > this._end)
                {
                    this._count = 0;
                    this._end = DateTime.Now + this.TimeFrame;
                }
                this._count++;
                if (((RunStatus) this.DecoratedChild.LastStatus) == RunStatus.Failure)
                {
                    yield return RunStatus.Failure;
                }
                else
                {
                    yield return RunStatus.Success;
                }
            }
            else
            {
                yield return this._limitStatus;
            }
        }

        public override void Start(object context)
        {
            base.Start(context);
        }

        public override void Stop(object context)
        {
            base.Stop(context);
        }

        public int Limit { get; set; }

        public TimeSpan TimeFrame { get; set; }

    }
}

